<template>
  <div class="app-container">
    <ResizeBox :treeData="treeData" @pitchOnData="pitchOnData">
      <template>
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          v-show="showSearch"
          label-width="80px"
        >
          <el-form-item label="管控方式" prop="dataSrc">
            <el-select
              v-model="queryParams.dataSrc"
              placeholder="请选择管控方式"
              style="width: 100%"
            >
              <el-option
                v-for="item in dict.type.data_src"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['syf:measure:add']"
              >新增</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['syf:measure:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['syf:measure:remove']"
              >删除</el-button
            >
          </el-col>
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>

        <el-table
          v-loading="loading"
          :data="measureList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column
            label="安全风险对象"
            align="center"
            prop="objectName"
          />
          <el-table-column
            label="安全风险单元"
            align="center"
            prop="unitName"
          />
          <el-table-column label="风险事件" align="center" prop="accidentName" />
          <el-table-column label="管控方式" align="center" prop="dataSrc" />
          <el-table-column label="管控措施" align="center" prop="measureType" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ `${scope.row.measureType}/${scope.row.measureSubType}/${scope.row.measureOtherType}` }}
            </template>
          </el-table-column>
          <el-table-column label="措施描述" align="center" prop="description" show-overflow-tooltip/>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['syf:measure:edit']"
                >修改</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['syf:measure:remove']"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />

        <!-- 添加或修改管控措施对话框 -->
        <el-dialog
          :title="title"
          :visible.sync="open"
          width="1000px"
          append-to-body
        >
          <el-form ref="form" :model="form" :rules="rules" label-width="120px">
            <div v-if="type == 'add'">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="安全风险对象" prop="objectId">
                    <el-select
                      v-model="form.objectId"
                      filterable
                      remote
                      reserve-keyword
                      placeholder="请输入安全风险对象"
                      :remote-method="remoteMethodObject"
                      @change="changeObject"
                      :loading="loadingObject"
                      style="width: 100%"
                    >
                      <el-option
                        v-for="item in objectDate"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="安全风险单元" prop="unitId">
                    <el-select
                      v-model="form.unitId"
                      @change="changeUnit"
                      placeholder="请选择安全风险单元"
                      style="width: 100%"
                    >
                      <el-option
                        v-for="item in unitDate"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="24">
                  <el-form-item prop="detailId" label="风险事件:">
                    <el-select
                      v-model="form.detailId"
                      placeholder="请选择风险事件"
                      style="width: 100%"
                    >
                      <el-option
                        v-for="item in detailDate"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="12">
                  <el-form-item label="管控方式" prop="dataSrc">
                    <el-select
                      v-model="form.dataSrc"
                      placeholder="请选择管控方式"
                      style="width: 100%"
                    >
                      <el-option
                        v-for="item in dict.type.data_src"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="措施分类" prop="measureType">
                    <el-cascader
                      v-model="measureTypes"
                      :options="measureTypeOptions"
                      @change="handleChangeMeasureTypes"
                      placeholder="请选择措施分类"
                      clearable
                      style="width: 100%"
                    ></el-cascader>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>

            <div v-else>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="安全风险对象">
                    <el-input v-model="form.objectName" disabled/>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="安全风险单元">
                    <el-input v-model="form.unitName" disabled/>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="24">
                  <el-form-item label="风险事件:">
                    <el-input v-model="form.accidentName" disabled/>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="12">
                  <el-form-item label="管控方式" prop="dataSrc">
                    <el-select
                      v-model="form.dataSrc"
                      placeholder="请选择管控方式"
                      style="width: 100%"
                    >
                      <el-option
                        v-for="item in dict.type.data_src"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="措施分类" prop="measureType">
                    <el-cascader
                      v-model="measureTypes"
                      :options="measureTypeOptions"
                      @change="handleChangeMeasureTypes"
                      placeholder="请选择措施分类"
                      clearable
                      style="width: 100%"
                    ></el-cascader>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>

            <el-row>
              <el-col :span="24">
                <el-form-item label="措施三级分类" prop="measureOtherType">
                  <el-input
                    v-model="form.measureOtherType"
                    placeholder="请输入内容"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="措施描述" prop="description">
              <el-input
                v-model="form.description"
                type="textarea"
                placeholder="请输入措施描述"
              />
            </el-form-item>
            <el-form-item label="排查内容" prop="content">
              <el-input
                v-model="form.content"
                type="textarea"
                placeholder="请输入排查内容"
              />
            </el-form-item>
            <el-form-item prop="status" label="配置排查任务:">
              <el-switch v-model="form.status"></el-switch>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>
      </template>
    </ResizeBox>
  </div>
</template>

<script>
import {
  listMeasure,
  getMeasure,
  delMeasure,
  addMeasure,
  updateMeasure,
} from "@/api/syf/risk/measure";
import { evaluationTree } from "@/api/syf/tree";
import ResizeBox from "@/components/syf/ResizeBox/index";

export default {
  name: "Measure",
  components: { ResizeBox },
  dicts: [
    "risk_level",
    "data_src",
    "measure_type",
    "project_skill",
    "tpm",
    "operation_behavior",
    "emergency_measure",
  ],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 管控措施表格数据
      measureList: [],
      // 风险树
      treeData: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        detailIds: [],
        dataSrc: null,
      },
      loadingObject: false,
      objectDate: [],
      unitDate: [],
      detailDate: [],
      measureTypes: [],
      measureTypeOptions: [],
      type: "add",
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        objectId: [
          {
            required: true,
            message: "安全风险对象不能为空",
            trigger: "blur",
          },
        ],
        unitId: [
          {
            required: true,
            message: "安全风险单元不能为空",
            trigger: "blur",
          },
        ],
        detailId: [
          {
            required: true,
            message: "风险事件不能为空",
            trigger: "blur",
          },
        ],
        dataSrc: [
          {
            required: true,
            message: "管控方式不能为空",
            trigger: "change",
          },
        ],
        measureType: [
          {
            required: true,
            message: "管控措施不能为空",
            trigger: "change",
          },
        ],
        description: [
          {
            required: true,
            message: "措施描述不能为空",
            trigger: "change",
          },
        ],
        content: [
          {
            required: true,
            message: "排查内容不能为空",
            trigger: "change",
          },
        ],
      },
    };
  },
  created() {
    this.getTreeData();
    this.getList();
    this.getMeasureTypeOptions();
  },
  methods: {
    /** 查询管控措施列表 */
    getList() {
      this.loading = true;
      listMeasure(this.queryParams).then((response) => {
        this.measureList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        objectId: null,
        unitId: null,
        detailId: null,
        measureType: null,
        measureSubType: null,
        measureOtherType: null,
        dataSrc: null,
        description: null,
        content: null,
        status: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        delFlag: null,
        firmId: null,
      };
      this.measureTypes = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.type = "add";
      this.title = "添加管控措施";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getMeasure(id).then((response) => {
        this.form = response.data;
        this.measureTypes[0] = this.form.measureType;
        this.measureTypes[1] = this.form.measureSubType;
        this.open = true;
        this.type = "update";
        this.title = "修改管控措施";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateMeasure(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMeasure(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除管控措施编号为"' + ids + '"的数据项？')
        .then(function () {
          return delMeasure(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 查询树数据 */
    getTreeData() {
      evaluationTree().then((res) => {
        this.treeData = res.data;
      });
    },
    //选中树节点
    pitchOnData(val) {
      let detailIds = [];
      val.forEach((item) => {
        detailIds.push(item.id);
      });
      this.queryParams.detailIds = detailIds;
      this.handleQuery();
    },
    //查询对象
    remoteMethodObject(query) {
      if (query !== "") {
        this.loadingObject = true;
        setTimeout(() => {
          this.loadingObject = false;
          this.objectDate = this.treeData.filter((item) => {
            return item.name.toLowerCase().indexOf(query.toLowerCase()) > -1;
          });
        }, 200);
      } else {
        this.objectDate = [];
      }
    },
    //选中对象
    changeObject(val) {
      for (var index in this.objectDate) {
        if (val == this.objectDate[index].id) {
          this.unitDate = this.objectDate[index].children;
          break;
        }
      }
    },
    //选中单元
    changeUnit(val) {
      for (var index in this.unitDate) {
        if (val == this.unitDate[index].id) {
          this.detailDate = this.unitDate[index].children;
          break;
        }
      }
    },
    //获取措施分类
    async getMeasureTypeOptions() {
      this.measureTypeOptions = [];
      let data = await this.getDictData("measure_type");
      let measure_type = JSON.parse(JSON.stringify(data));
      for (let item of measure_type) {
        let children = [];
        let dictType = item.value;
        let data2 = await this.getDictData(dictType);
        let val = JSON.parse(JSON.stringify(data2));
        val.forEach((item2) => {
          children.push({
            value: item2.value,
            label: item2.label,
          });
        });
        this.measureTypeOptions.push({
          value: item.value,
          label: item.label,
          children: children,
        });
      }
    },
    getDictData(type) {
      return this.dict.type[type] || [];
    },
    //选中措施分类
    handleChangeMeasureTypes() {
      this.form.measureType = this.measureTypes[0];
      this.form.measureSubType = this.measureTypes[1];
    },
  },
};
</script>
